package o2o.web.actions.divide;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.divide.DividingInfoMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.divide.DIVIDING_CODE;
import o2o.dao.PO.divide.DIVIDING_TYPE;
import o2o.dao.PO.divide.DividingInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.divide.DividingInfoVO;
import o2o.web.actions.user.User;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DividingAction {


    @RequestMapping("/city/divide/get")
    public String divide_info_get(String token, String city) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //是否有权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请选择城市");
        }
        if (city.trim().endsWith("市")) {
            city = city.substring(0, city.lastIndexOf("市"));
        }
        if (ValidateUtil.isNull(city)) {
            return AjaxResult.errorResult("请选择城市");
        }
        DividingInfo info = DividingMan.getShopPacketDividingInfoByCity(city);
        if (info == null) {
            return AjaxResult.successResult();
        }
        DividingInfoVO infoVO = new DividingInfoVO();
        try {
            ObjectUtils.copyPropertiesExclude(info, infoVO);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后重试");
        }
        return AjaxResult.successResult(infoVO);
    }

    // 获取指定类型的商圈固定配送抽成
    @RequestMapping("/admin/city-agent/divide/list")
    public String listCityAgentDivide(String token, Long agentId, Long shopId, Integer code) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNotID(shopId) && agentId == null) {
            agentId = -1L;
        }
        List<DividingInfo> list = null;
        if (ValidateUtil.isID(shopId)) {
            list = DividingInfoMemory.getInstance().listOfDivideByShopId(shopId, code);
        } else {
            list = DividingInfoMemory.getInstance().listOfDivide(null, agentId, code);
        }
        if (ValidateUtil.isAbsList(list)) {
            List<DividingInfoVO> infoVOS = list.stream().map(item -> {
                DividingInfoVO vo = new DividingInfoVO();
                BeanUtils.copyProperties(item, vo);
                return vo;
            }).collect(Collectors.toList());
            Collections.sort(infoVOS, Comparator.comparingDouble(DividingInfoVO::getMoneyRang));
            return AjaxResult.successResult(infoVOS.size(), infoVOS);
        }
        return AjaxResult.successResult(null, 0);
    }

    // 删除抽佣
    @RequestMapping("/admin/city-agent/divide/del")
    public String listCityAgentDivide(String token, Long id) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        DividingInfo dividingInfo = DividingInfoMemory.getInstance().getById(id);
        if (dividingInfo == null) {
            return AjaxResult.errorResult("未获到抽佣设置信息");
        }
        String delSql = "update " + PojoTables.DIVIDING_INFO + " set delFlag = 1 ,updateUser ='" + user.getUsername() + "' where delFlag = 0 and id = " + id;
        try {
            UserDaoSql.getInstance().executeBySql(delSql);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        try {
            DividingInfoMemory.getInstance().modify(id);
            // 数据通讯
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.DIVIDING_INFO_UPDATE).setLong01(id);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.successResult();
    }

    // 添加或者修改
    @RequestMapping("/city/divide/add-update")
    public String divide_info_modify(String token, DividingInfo info) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //是否有权限
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }
        if (info.getType() == 0) {
            info.setType(DIVIDING_TYPE.DIVIDING_TYPE_CITY);
        }
        if (info.getType() - DIVIDING_TYPE.DIVIDING_TYPE_CITY == 0) {
            if (ValidateUtil.isNull(info.getCity())) {
                return AjaxResult.errorResult("城市信息不能为空");
            }
            String city = info.getCity();
            if (city.trim().endsWith("市")) {
                city = city.substring(0, city.lastIndexOf("市"));
            }
            info.setCity(city);
        }
        if (info.getCode() - DIVIDING_CODE.SHOP_PACKET != 0 && info.getCode() - DIVIDING_CODE.PLATE_CHOU_YONG != 0) {
            info.setCode(DIVIDING_CODE.SHOP_PACKET);
        }
        DividingInfo infoDB = null;
        if (info.getCode() == DIVIDING_CODE.SHOP_PACKET) {
            if (ValidateUtil.isNotAbsDouble(info.getShopPacketRate())) {
                return AjaxResult.errorResult("打包费分成不能为空");
            }
            if (info.getShopPacketRate() < 0 || info.getShopPacketRate() > 100) {
                return AjaxResult.errorResult("打包费分成在0-100之间");
            }
            infoDB = DividingInfoMemory.getInstance().getShopPacketShareDistributeInfoByCity(info.getCity(), DIVIDING_CODE.SHOP_PACKET);
        } else {
            if (info.getMoneyRang() == null || info.getMoneyRang() < 0) {
                return AjaxResult.errorResult("满足金额设置不正确");
            }
            if (info.getPlateChouYong() == null || info.getPlateChouYong() < 0) {
                return AjaxResult.errorResult("抽成金额不正确");
            }
            infoDB = DividingInfoMemory.getInstance().getById(info.getId());
        }
        if (infoDB != null) {
            if (ValidateUtil.isNotID(info.getId())) {
                return AjaxResult.errorResult("id不能为空");
            }
            // 更新
            StringBuffer sql = new StringBuffer();
            sql.append("update ").append(PojoTables.DIVIDING_INFO).append(" set updateUser='").append(user.getUsername())
                    .append("' ");
            if (info.getCode() - DIVIDING_CODE.SHOP_PACKET == 0) {
                sql.append(", shopPacketRate=").append(info.getShopPacketRate());
            } else {
                sql.append(", moneyRang =").append(info.getMoneyRang())
                        .append(",plateChouYong = ").append(info.getPlateChouYong());
            }
            String note = "";
            if (ValidateUtil.isNotNull(info.getNote())) {
                note = ",note = '" + info.getNote() + "'";
            }
            String descs = "";
            if (ValidateUtil.isNotNull(info.getDescs())) {
                descs = ",descs = '" + info.getDescs() + "'";
            }
            sql.append(note).append(descs).append(" where ")
                    .append(" id =").append(infoDB.getId()).append(" and delFlag = 0");
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("修改失败，请稍后重试");
            }
            DividingInfoMemory.getInstance().modify(info.getId());
            // 数据通讯
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.DIVIDING_INFO_UPDATE).setLong01(info.getId());
            JmsSender.setTopicSender(notify);
        } else {
            if (info.getAgentId() == null && ValidateUtil.isNotID(info.getShopId())) {
                info.setAgentId(-1L).setShopId(0L);
            } else if (ValidateUtil.isID(info.getShopId())) {
                info.setAgentId(0L);
            }
            // 插入
            long cTime = DateUtils.getCurrTime();
            info.setCreateUser(user.getUsername())
                    .setCreateTime(cTime)
                    .setId(null);
            if (ValidateUtil.isNotAbsDouble(info.getShopGoodsRate())
                    || info.getShopGoodsRate() < 0
                    || info.getShopGoodsRate() > 100) {
                info.setShopGoodsRate(0D);
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.DIVIDING_INFO, info);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.errorResult("更新失败，请稍后重试");
            }
            DividingInfoMemory.getInstance().add(cTime);
            // 数据通讯
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.DIVIDING_INFO_ADD).setLong01(cTime);
            JmsSender.setTopicSender(notify);
        }
        return AjaxResult.successResult();
    }


}